package org.luxor.commons.websocket.server;

import org.luxor.commons.websocket.WsSessionContextUtils;
import org.luxor.commons.websocket.annotation.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;


/**
 * 接收控制台打印日志
 *
 * @author Mr.yan  @date 2021/8/3
 */
@Component
@WebSocketServer("/websocket/console")
public class ConsoleServer {
    private static final Logger log = LoggerFactory.getLogger(ConsoleServer.class);

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("【ConsoleServer】建立新的连接(sessionId:{})", session.getId());
    }

    /**
     * 监听客户端发送的消息
     */
    @OnMessage
    public void onMessage(String message) {
        WsSessionContextUtils.sendAll(message);
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        log.info("【ConsoleServer】客户端关闭连接(sessionId:{})...", session.getId());
    }

    /**
     * 网络异常处理
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.warn("WebSocket网络出现异常.(sessionId:" + session.getId() + ")", error);
    }

}